<template>
  <div :style="{ height: activeHei + 'px' }">
    <yd-ls-layout :title="titles" :onfoot=false :tolfurl="urls">
      <div style="position:absolute;top:0;left:0;z-index: 9;overflow:auto;width:100%;" id="myData" :style="{ height: activeHei + 'px' }">
        <div class="yd-ls-height"></div>
        <yd-pullrefresh :callback="loadList" ref="pullrefreshDemo" :stopDrag="hasDrag">
          <yd-ls-message >
            <i class="msg-text" v-if="hasDrag">没有更多记录了</i>
            <i class="msg-text" v-if="!hasDrag">下拉加载更多</i>
            <div v-for="(msgInfo,index) in msgList" :key="index">
              <div v-for="(item,inds) in msgInfo.minutes" :key="inds">
                <i class="msg-text">{{ item.minute }}</i>
                <yd-ls-message-pearl v-for="(msgCon,ind) in item.items" :key="ind"
                                      :class="{'left-item': msgCon.user_type == 1, 'right-item': msgCon.user_type == 0}">
                  <span slot="img"><img :src="msgCon.head || defalut_img"/></span>
                  <span slot="message" v-if="msgCon.msg_type == 0">
                    <pre class="msg-con">{{ msgCon.rcd_contents }}</pre>
                  </span>
                  <span slot="message" :ismsg="{true : msgCon.msg_type == 1}" v-if="msgCon.msg_type == 1">
                    <p class="msg-con">
                      <!-- <yd-lightbox>
                          <yd-lightbox-img :src="msgCon.rcd_contents"></yd-lightbox-img>
                      </yd-lightbox> -->
                      <img :src="msgCon.rcd_contents" @click="previewImages(msgCon.rcd_contents)" class="preview-img"/>
                    </p>
                  </span>
                  <span slot="messageDurg" :ismsg="{false : msgCon.msg_type == 2}" v-if="msgCon.msg_type == 2" >
                    <div class="sick-case">
                      <span class="sick-case-hd">建议服用</span>
                      <div class="sick-case-bd"  v-for="(msgdrug,indx) in msgCon.druguse" :key="indx">
                        <p>{{ msgdrug.drug_name }} {{ msgdrug.common_name }}</p>
                        <p>{{ msgdrug.standard }}</p>
                        <p>需求数量：{{ msgdrug.qty }}盒</p>
                      </div>
                      <yd-button class="f-float-btn"
                                  v-if="msgCon.is_buy"
                                  size="large" bgcolor="#c8d4fc" color="#4871f1"
                                  @click.native="goOrder(msgCon.msg_id)">立即下单</yd-button>
                      <yd-button class="f-float-btn"
                                  v-if="!msgCon.is_buy"
                                  size="large" type="disabled" disabled>已经下单</yd-button>
                    </div>
                  </span>
                  <span slot="message" :ismsg="{true : msgCon.msg_type == 4}" v-if="msgCon.msg_type == 4">
                    <div class="msg-con">
                      <div @click="playAudio($event)">
                        播放录音
                        <yd-icon color="#999" size=".28rem" name="play"></yd-icon>
                      </div>
                      <audio :src="msgCon.rcd_contents" preload="auto"></audio>
                    </div>
                  </span>
                </yd-ls-message-pearl>
              </div>
            </div>
            <div class="yd-ls-height"></div>
          </yd-ls-message>
        </yd-pullrefresh>
      </div>
    </yd-ls-layout>

    <yd-ls-flex-button v-if="msgClose">
      <yd-flexbox>
        <yd-flexbox-item>
          <p>本次咨询已结束</p>
          <span>请为医生服务打个分吧</span>
        </yd-flexbox-item>
        <yd-button type="primary" @click.native="evalDot">{{ is_evaluate ? '已评价' : '评价医生' }}</yd-button>
        <yd-button type="warning" @click.native="chatCheck">再次咨询</yd-button>
      </yd-flexbox>
    </yd-ls-flex-button>
    <yd-ls-button v-if="!msgClose" btnname="咨询医生" @handle-button="chatCheck"></yd-ls-button>
  </div>
</template>

<script>
import ydLsBox from "../../../components/yd-ls-box.vue";
import ydLsLayout from "../../../components/yd-ls-layout.vue";
import ydLsMessage from "../../../components/yd-ls-message.vue";
import ydLsMessagePearl from "../../../components/yd-ls-message-pearl.vue";
import ydLsFlexButton from "../../../components/yd-ls-flexbutton.vue";
import ydLsButton from "../../../components/yd-ls-button.vue";
import wx from "wx";
import { mapGetters } from "vuex";
import api from "../../../axios/api";

export default {
  name: "message",
  data() {
    return {
      urls: "",
      titles: "消息详情",
      msgList: [],
      hasDrag: false,
      msgClose: false,
      getMsgid: 0,
      recodeId: 0,
      activeHei: 600,
      getMsgState: {},
      is_evaluate: false,
      defalut_img: api.default_img_dot // 医生缺省头像
    };
  },
  computed: {
    ...mapGetters({
      sid: "getMsgInfo"
    })
  },
  created() {
    //TODO: 从公众号或支付返回时，检查openid
    if(this.$route.query.openid){
      localStorage.openId = this.$route.query.openid
    }
    
    //TODL: 初始化数据
    this.activeHei = document.body.scrollHeight
    this.hasDrag = false;
    this.titles = this.$route.query.drname;
    let drid = this.$route.query.drid;
    let msgid = this.$route.query.msgid || 0;
    let type = this.$route.query.type;
    if(type=="seek"){
      this.urls = `seek.html`; // 哪里进，回哪里去
    }else{
      this.urls = `index.html#/${type}?drid=${drid}`; // 哪里进，回哪里去
    }
    
    this.msgList.length = 0; // 重新进页面清空消息列表缓存
    
    //TODO: 从公众号或支付返回时，重新加载数据
    setTimeout(()=>{
      this.getMsgList(drid,msgid);
      this.getMsgClose(drid)
    }, 800)
  },
  methods: {
    getMsgList(drid,msgid) {
      this.$dialog.loading.open(api.default_loading_txt);
      this.axios.get(api.msg_info,{params: {drid: drid,msg_id: msgid}})
        .then(m=>{
          //消息列表
            let msg_info_data = m.data;
            
            if(!msg_info_data.data || msg_info_data.data===null){
              this.hasDrag = true
            }else{
              this.hasDrag = false
              this.msgList = this.msgList.concat(msg_info_data.data) || [];
              this.is_evaluate = msg_info_data.data.is_evaluate
            }
            
            this.rollBottom()
        }).catch(err=>{
          this.$dialog.loading.close()
          this.$dialog.alert({mes: 'msg_info=' + JSON.stringify(err)})
        })
    },
    getMsgClose(drid) {
      this.axios.get(api.msg_colse, { params: { drid: drid }})
        .then(m=>{
          //是否关闭咨询
            let msg_colse_data = m.data;
            this.getMsgState = msg_colse_data.data
            this.msgClose = this.getMsgState.is_close;
            this.recodeId = this.getMsgState.current_msg_id;
            this.$dialog.loading.close()
        }).catch(err=>{
          this.$dialog.loading.close()
          this.$dialog.alert({mes: 'msg_colse=' + JSON.stringify(err)})
        })
    },
    evalDot() {
      let params = {
        pagename: "msg", 
        drname: this.$route.query.drname,
        drid: this.$route.query.drid, 
        msgid: this.$route.query.msgid || 0, 
        rid: this.recodeId, 
        type: 1
      }
      this.$router.push({path: "evals", query: params});
    },
    chatCheck() {
      this.$dialog.loading.open(api.default_loading_txt);
      this.axios.get(api.msg_check, {params: {drid: this.$route.query.drid}})
        .then(m=>{
          let msg_check_data = m.data
          if(msg_check_data.data) {
            this.$dialog.confirm({
              title: '咨询医生',
              mes: `你目前和${msg_check_data.data}医生的咨询尚未结束，不能开展其他咨询，是否先结束上次咨询？`,
              opts: [
                      {
                        txt: '取消',
                        color: false
                      },
                      {
                        txt: '确定',
                        color: true,
                        stay: true,
                        callback: () => {
                            this.chatDot(true)
                        }
                      }
                    ]
            });
            this.$dialog.loading.close()
          }else {
            this.chatDot(false)
          }
        }).catch(err=>{
          this.$dialog.loading.close()
          this.$dialog.alert({mes: 'msg_check=' + JSON.stringify(err)})
        })
    },
    chatDot(isclose) {
      let _this = this
      let msgInfo = this.getMsgState.pay_info

      //直接咨询
      const consultDr = ()=>{
        this.axios.get(api.msg_wx, {
          params: {
            drid: this.$route.query.drid,
            doctor_name: this.$route.query.drname,
            is_auto_close: isclose,
            order_id: this.getMsgState.order_id
          }
        }).then(m => {
          let msg_wx_data = m.data;
          this.$dialog.loading.close()
          if (msg_wx_data.retcode == 0) {
            WeixinJSBridge.call("closeWindow"); //关闭当前窗口，回到公众号l
          } else {
            let mes = msg_wx_data.retmsg;
            this.$dialog.alert({mes: JSON.stringify(mes)})
          }
        }).catch(err=>{
          this.$dialog.loading.close()
          this.$dialog.alert({mes: 'msg_wx=' + JSON.stringify(err)})
        })
      }
      //去支付
      const payAction = ()=> {
        let payinfo = {}
        let params = {
          drid: this.$route.query.drid,
          total_fee: this.getMsgState.pay_info.pay_money
        }
        this.axios.post(api.msg_payinfo, params)
        .then(m=>{
          payinfo = m.data.data
          payinfo.type = 4
          payinfo.openid = localStorage.openId
          payinfo.drname = this.$route.query.drname
          payinfo.drid = this.$route.query.drid
          payinfo.msgid = this.$route.query.msgid || 0
          payinfo.pagetype = this.$route.query.type
          
          //存基本信息，跳支付页
          this.axios.get('http://nkwx.6ewei.com/pay/payinfo.aspx', {
            params: {
              openid: localStorage.openId,
              payinfo: payinfo
            }
          })
          .then(m=>{

            window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx75d21642db594aca&redirect_uri=http%3A%2F%2Fhtpay.6ewei.com%2Findex.html&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
            // window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxbe6733023cdd7b1e&redirect_uri=http://pay.6ewei.com/index.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
          }).catch(err=>{
            this.$dialog.loading.close()
            this.$dialog.alert({mes: 'payinfo=网络出错'})
          })
        }).catch(err=>{
          this.$dialog.loading.close()
          this.$dialog.alert({mes: 'buildMsgOrder=' + JSON.stringify(err.response.status)})
        })
      }

      //是否设置可付费咨询
      if(this.getMsgState.is_set_pay) {
        //是否有可用的订单
        if(this.getMsgState.is_avaliable_order) {
          //直接咨询
          consultDr()
        }else {
          //支付
          this.$dialog.confirm({
            title: '图文咨询服务',
            mes: `${msgInfo.dr_name}医生图文咨询服务为 ${msgInfo.pay_money}元/次，支付后再次点击“咨询医生”即可发起对话`,
            opts: [
              {
                txt: '取消',
                color: false,
                callback: () => {
                  _this.$dialog.loading.close()
                }
              },
              {
                txt: '确定',
                color: true,
                stay: true,
                callback: () => {
                  payAction()
                }
              }
          ],
            
          });
        }
      }else {
        //免费+直接咨询
        consultDr()
      }

    },
    loadList() {
      this.axios.get(api.msg_more, {
          params: {
            drid: this.$route.query.drid,
            date: this.msgList[0].date
          }
        }).then(m => {
          let msg_list_data = m.data;
          if (!msg_list_data.data) {
            this.hasDrag = true;
            this.$refs.pullrefreshDemo.$emit("ydui.pullrefresh.finishLoad");
            return;
          }
          this.msgList.splice(0, 0, msg_list_data.data);
          this.$refs.pullrefreshDemo.$emit("ydui.pullrefresh.finishLoad");
        })
        .catch(err => {
          this.hasDrag = true;
          this.$refs.pullrefreshDemo.$emit("ydui.pullrefresh.finishLoad");
        });
    },
    playAudio(ev) {
      let myAudio = ev.target.parentNode.children[1];
      let audio = document.getElementsByTagName("audio");
      for (let i = 0; i < audio.length; i++) {
        audio[i].pause();
        audio[i].currentTime = 0;
      }
      setTimeout(() => {
        myAudio.play();
      }, 100);
    },
    goOrder(msgid) {
      window.location.href = `${api.shop_host}/smg-microMallForeEnd/mobileBuyCartAction!goShoppingCart.action?openid=${localStorage.openId}&ramid=${new Date()}`
    },
    rollBottom() {
      setTimeout(function() {
        document.getElementById('myData').scrollTop = document.getElementById('myData').scrollHeight
      }, 100);
    },
    previewImages(img) {
      const imgs = document.querySelectorAll('.preview-img');
      const arrayImg = Array.from(imgs);
      const newImg = []
      for(let i=0; i<arrayImg.length; i++) {
        newImg[i] = arrayImg[i].src
      }
      wx.previewImage({
        current: img, // 当前显示图片的http链接
        urls: newImg // 需要预览的图片http链接列表
      });
    },
  },
  mounted() {},
  components: {
    ydLsBox,
    ydLsLayout,
    ydLsMessage,
    ydLsMessagePearl,
    ydLsFlexButton,
    ydLsButton
  }
};
</script>

<style>
pre.msg-con {
  white-space: pre-wrap;
  word-break: break-all;
  line-height: .5rem;
}
</style>